package com.ywz.project.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ywz.common.ResultResp;
import com.ywz.common.StringUtils;
import com.ywz.project.base.system.entity.TSysPermission;
import com.ywz.project.base.system.entity.TSysRole;
import com.ywz.project.base.system.entity.TSysRolePermission;
import com.ywz.project.base.system.service.TSysPermissionService;
import com.ywz.project.base.system.service.TSysRolePermissionService;
import com.ywz.project.base.system.service.TSysRoleService;
import com.ywz.project.system.dto.req.EditRoleReq;
import com.ywz.project.system.dto.req.RolePageReq;
import com.ywz.project.system.dto.resp.RolePageResp;
import com.ywz.project.system.service.RoleApiService;
import jakarta.annotation.Resource;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class RoleApiServiceImpl implements RoleApiService {
    @Resource
    private TSysRoleService tSysRoleService;
    @Resource
    private TSysRolePermissionService tSysRolePermissionService;
    @Resource
    private TSysPermissionService tSysPermissionService;

    @Override
    public ResultResp getRolePage(RolePageReq req) {
        LambdaQueryWrapper<TSysRole> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(TSysRole::getIsDeleted, 0);
        queryWrapper.like(!StringUtils.isEmpty(req.getRoleName()), TSysRole::getRoleName, req.getRoleName());
        // 获取角色分页
        Page<TSysRole> page = tSysRoleService.page(new Page<>(req.getPageNum(), req.getPageSize()), queryWrapper);
        // 获取角色权限关联
        LambdaQueryWrapper<TSysRolePermission> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(TSysRolePermission::getIsDeleted, 0);
        List<TSysRolePermission> rolePermissionlist = tSysRolePermissionService.list(wrapper);
        // 获取权限列表
        LambdaQueryWrapper<TSysPermission> permissionWrapper = new LambdaQueryWrapper<>();
        permissionWrapper.eq(TSysPermission::getIsDeleted, 0);
        List<TSysPermission> permissionList = tSysPermissionService.list(permissionWrapper);
        // 组装响应数据
        Page<RolePageResp> pageResp = new Page<>();
        pageResp.setCurrent(page.getCurrent());
        pageResp.setSize(page.getSize());
        pageResp.setTotal(page.getTotal());
        List<RolePageResp> records = page.getRecords().stream().map(role -> {
            RolePageResp resp = new RolePageResp();
            BeanUtils.copyProperties(role, resp);
            // 获取角色权限id
            List<Integer> permissionIds = rolePermissionlist.stream().filter(rolePermission -> rolePermission.getRoleId().equals(role.getId())).map(TSysRolePermission::getPermissionId).toList();
            // 获取对应权限
            List<TSysPermission> permissions = permissionList.stream().filter(permission -> permissionIds.contains(permission.getId())).collect(Collectors.toList());
            resp.setPermissions(permissions);
            resp.setPermissionName(permissions.stream().map(TSysPermission::getPermissionName).collect(Collectors.joining(",")));
            return resp;
        }).collect(Collectors.toList());
        if (!StringUtils.isEmpty(req.getPermissionName())) {
            records = records.stream().filter(role -> role.getPermissionName().contains(req.getPermissionName())).collect(Collectors.toList());
        }
        pageResp.setRecords(records);
        return ResultResp.success(pageResp);
    }

    @Override
    public ResultResp getRoleListByUserId(Integer userId) {
        List<TSysRole> roleListByUserId = tSysRoleService.getRoleListByUserId(userId);
        return ResultResp.success(roleListByUserId);
    }

    @Override
    public ResultResp editRole(EditRoleReq req) {
        // 参数校验
        if (StringUtils.isEmpties(req.getPermissionIds(), req.getRoleName(), req.getRoleType()))
            return ResultResp.error("参数不能为空");
        if (StringUtils.isNull(req.getStatus()))
            return ResultResp.error("状态不能为空");
        if (StringUtils.isOverLength(255, req.getRoleDesc(), req.getRemark(), req.getRoleName(), req.getRoleType()))
            return ResultResp.error("参数长度超过限制");

        // 保存角色信息
        TSysRole sysRole = new TSysRole();
        BeanUtils.copyProperties(req, sysRole);
        sysRole.setUpdatedTime(LocalDateTime.now());
        boolean saved = tSysRoleService.saveOrUpdate(sysRole);
        if (!saved)
            return ResultResp.error();
        // 删除已关联的角色权限
        LambdaUpdateWrapper<TSysRolePermission> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(TSysRolePermission::getRoleId, req.getId());
        tSysRolePermissionService.remove(updateWrapper);
        // 重新角色权限关联
        if (StringUtils.isNumberAndSeparator(req.getPermissionIds())) {
            String[] split = req.getPermissionIds().split(StringUtils.SEPARATOR);
            List<TSysRolePermission> rolePermissions = new ArrayList<>();
            for (String permissionId : split) {
                TSysRolePermission rolePermission = new TSysRolePermission();
                rolePermission.setRoleId(sysRole.getId());
                rolePermission.setPermissionId(Integer.parseInt(permissionId));
                rolePermissions.add(rolePermission);
            }
            tSysRolePermissionService.saveBatch(rolePermissions);
        }
        return ResultResp.success();
    }

    @Override
    public ResultResp removeRole(String ids) {
        if (StringUtils.isNumberAndSeparator(ids)) {
            // 分割字符串并转成int集合
            List<Integer> roleIdList = Arrays.stream(ids.split(StringUtils.SEPARATOR)).map(Integer::parseInt).collect(Collectors.toList());
            // 删除角色权限关联
            LambdaUpdateWrapper<TSysRolePermission> updateWrapper = new LambdaUpdateWrapper<>();
            updateWrapper.in(TSysRolePermission::getRoleId, roleIdList);
            tSysRolePermissionService.remove(updateWrapper);
            // 标记角色为删除状态
            LambdaUpdateWrapper<TSysRole> updateWrapper2 = new LambdaUpdateWrapper<>();
            updateWrapper2.in(TSysRole::getId, roleIdList);
            updateWrapper2.set(TSysRole::getIsDeleted, 1);
            updateWrapper2.set(TSysRole::getUpdatedTime, LocalDateTime.now());
            boolean updated = tSysRoleService.update(updateWrapper2);
            if (updated)
                return ResultResp.success();
        }
        return ResultResp.error();
    }

    @Override
    public ResultResp getRoleList() {
        LambdaQueryWrapper<TSysRole> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(TSysRole::getIsDeleted, 0);
        List<TSysRole> list = tSysRoleService.list(queryWrapper);
        return ResultResp.success(list);
    }
}
